﻿using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EventBus
{
   public class IocEventHandlerFactory : IEventHandlerFactory
    {

        private readonly IServiceProvider _serviceScopeFactory;
        private readonly Type _handlerType;

        /// <summary>
        /// 初始化一个<see cref="IocEventHandlerFactory"/>类型的新实例
        /// </summary>
        /// <param name="serviceScopeFactory">服务作用域工厂</param>
        /// <param name="handlerType">事件处理器类型</param>
        public IocEventHandlerFactory(IServiceProvider serviceScopeFactory, Type handlerType)
        {
            _serviceScopeFactory = serviceScopeFactory;
            _handlerType = handlerType;
        }



        /// <summary>
        /// 获取事件处理器实例
        /// </summary>
        /// <returns></returns>
        public EventHandlerDisposeWrapper GetHandler()
        {
            IServiceScope scope = _serviceScopeFactory.CreateScope();
            return new EventHandlerDisposeWrapper((IEventHandler)scope.ServiceProvider.GetService(_handlerType), () => scope.Dispose());
        }

        public Type GetHandlerType()
        {
           return _handlerType;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public Type GetArgumentType()
        {
            Type handlerInterfaceType = _handlerType.GetInterfaces().Where(i => i.IsGenericType&&(i.GetGenericTypeDefinition() == typeof(IEventHandler<>) || i.GetGenericTypeDefinition() == typeof(IEventHandlerAsnyc<>))).FirstOrDefault();
            if (handlerInterfaceType is null)
            {
                return null;
            }
         
            Type eventDataType = handlerInterfaceType.GetGenericArguments()[0];
            return eventDataType;
        }
    }
}
